package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.metagurukul.metagranth.service.UserService;
import com.metagurukul.metagranth.util.Validator;
import com.metagurukul.metagranth.vo.User;

/**
 * Servlet implementation class RegistrationServlet
 * This servlet performs the functionality of Registration of a new user.(SignUp Module)
 * @author team MetaGranth
 *
 */
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistrationServlet() {
		super();
	
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * this function is called during the registration process
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// to store all errors if validation fails @ Server side
		Map<String, String> errorMap = new HashMap<String, String>();  
		// Creates a new object of Validator class that has all the functions of validate 
		Validator validate = new Validator();   
		RequestDispatcher rd = null;
		boolean errorFlag = false;
		System.out.println("up");
		if (!validate.checkBlank(request.getParameter("username"))) {     //checks if username is null
			errorMap.put("username", "Please enter your Username");
			errorFlag = true;
		}
		/* Check for validation of Username */
		else if (!validate.emailValidate(request.getParameter("username"))) {
			errorMap.put("username", "Invalid Username");
			errorFlag = true;
		}
		if (!validate.checkBlank(request.getParameter("password"))) {      //checks if password is null
			errorMap.put("password", "Please enter your Password");
			errorFlag = true;
		}
		if (!validate.checkBlank(request.getParameter("conPassword"))) {		//checks if confirmPassword is null
			errorMap.put("confirmPassword",
					"Please enter your Confirm Password");
			errorFlag = true;
		}
		/* Check for validation of Password = Confirm Password */
		else if (!validate.passwordMatcher((request.getParameter("password")),
				request.getParameter("conPassword"))) {
			errorMap.put("confirmPassword",
					"Confirm Password should be same as Password");
			errorFlag = true;
		}
		if (errorFlag) {
			System.out.println("if");
			request.setAttribute("errorHashMap", errorMap);
			rd = request.getRequestDispatcher("signup.jsp");
			rd.forward(request, response);
		}

		else {
			String username = request.getParameter("username");
			String name = request.getParameter("name");
			String password = request.getParameter("password");
			String conPassword = request.getParameter("conPassword");
			String age = request.getParameter("age");

			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			user.setName(name);
			user.setAge(Integer.parseInt(age));

			

			/* begining of try-catch block */

			try {
				int statusIfRecordInserted = UserService.saveUserInformation(user);
					if (statusIfRecordInserted == 1) {
						// On success, redirect to home.jsp
						rd = request.getRequestDispatcher("success.jsp");     

					} 
				else if (statusIfRecordInserted == -1) {          
					errorMap.put("username", "Username already exists!");
					request.setAttribute("errorHashMap", errorMap);
					rd = request.getRequestDispatcher("signup.jsp");

				}else  {        // some technical glitch(SQL error)
					request.setAttribute("msg","Account cannot be created due to some internal error! Please try after some time");
					rd = request.getRequestDispatcher("signup.jsp");
				}
				rd.forward(request, response);
			} catch (Exception exception) {
				request.setAttribute("errormsg", exception.getMessage());
				request.getRequestDispatcher("errorPage.jsp").forward(request, response);

			} /* end of try - catch block */

		}/* End of First if clause in doPerform function */
	}

}
